﻿using System;
using System.Diagnostics;
using System.IO;
using System.Windows;
using GalaSoft.MvvmLight.Messaging;
using Miris.HumanMilkAnalyser.Service;
using Miris.HumanMilkAnalyser.Service.Shared;
using Miris.HumanMilkAnalyser.WPF.Shared;
using Miris.HumanMilkAnalyser.WPF.ViewModel;

namespace Miris.HumanMilkAnalyser.WPF
{
    /// <summary>
    /// Interaction logic for DataManagementPage.xaml
    /// </summary>
    public partial class DataManagementPage : PageBase
    {
        public const string SelectedDataSourceFileMessageToken = "DataManagementPageSelectedDataSourceFileMessage";
        public const string SelectedPatientDataFileMessageToken = "DataManagementPageSelectedPatientDataFileMessage";
        public const string SelectedExportTestReportFileMessageToken = "DataManagementPageSelectedExportTestReportFileMessage";

        public DataManagementPage()
        {
            InitializeComponent();
            InitializePageUnloadStoryboard();
        }

        protected override void RegisterMessages()
        {
            base.RegisterMessages();

            RegisterRequestDisplayOpenDataSourceFileDialogMessage();
            RegisterRequestDisplayOpenPatientDataFileDialogMessage();
            RegisterRequestDisplaySaveExportTestReportFileDialogMessage();
            RegisterRequestDisplaySaveExportMiniLogFileDialogMessage();
            RegisterCleanDataSourceConfirmMessage();
        }

        /// <summary>
        /// Register RequestDisplayOpenDataSourceFileDialogMessage from DataManagementViewModel
        /// </summary>
        private void RegisterRequestDisplayOpenDataSourceFileDialogMessage()
        {
            Messenger.Default.Register<int>(this, DataManagementViewModel.RequestDisplayOpenDataSourceFileDialogMessageToken, p =>
            {
                var openFileDialog = ViewHelper.CreateOpenFileDialog("导出的数据库文件|*" + DataSourceManagementService.ExportDataSourceFileExtension,
                    "选择需要导入的数据库文件", ConfigFileUtility.GetDataSourceFileExportPathFullName());
                openFileDialog.ShowDialog();

                if (!string.IsNullOrEmpty(openFileDialog.FileName))
                {
                    // Send SelectedDataSourceFileMessage to DataManagementViewModel
                    Messenger.Default.Send<string>(openFileDialog.FileName, SelectedDataSourceFileMessageToken);
                }
            });
        }

        /// <summary>
        /// Register RequestDisplayOpenPatientDataFileDialogMessage from DataManagementViewModel.
        /// </summary>
        private void RegisterRequestDisplayOpenPatientDataFileDialogMessage()
        {
            Messenger.Default.Register<int>(this, DataManagementViewModel.RequestDisplayOpenPatientDataFileDialogMessageToken, p =>
            {
                var openFileDialog = ViewHelper.CreateOpenFileDialog("导出的被测者数据文件|*" + DataSourceManagementService.ExportPatientDataFileExtension,
                    "选择需要导入的被测者数据文件", ConfigFileUtility.GetPatientDataExportPathFullName());
                openFileDialog.ShowDialog();

                if (!string.IsNullOrEmpty(openFileDialog.FileName))
                {
                    // Send SelectedPatientDataFileMessage to DataManagementViewModel
                    Messenger.Default.Send<string>(openFileDialog.FileName, SelectedPatientDataFileMessageToken);
                }
            });
        }

        /// <summary>
        /// Register RequestDisplaySaveExportTestReportFileDialogMessage from DataManagementViewModel.
        /// </summary>
        private void RegisterRequestDisplaySaveExportTestReportFileDialogMessage()
        {
            Messenger.Default.Register<int>(this, DataManagementViewModel.RequestDisplaySaveExportTestReportFileDialogMessageToken, p =>
            {
                var saveFileDialog = ViewHelper.CreateSaveFileDialog("测试报告文件|*" + DataSourceManagementService.ExportTestReportFileExtension,
                    DataSourceManagementService.ExportTestReportFileExtension, "保存测试报告");
                saveFileDialog.ShowDialog();

                if (!string.IsNullOrEmpty(saveFileDialog.FileName))
                {
                    // Send SelectedExportTestReportFileMessage to DataManagementViewModel
                    Messenger.Default.Send<string>(saveFileDialog.FileName, SelectedExportTestReportFileMessageToken);
                }
            });
        }

        /// <summary>
        /// Register RequestDisplaySaveExportMiniLogFileDialogMessage from DataManagementViewModel.
        /// </summary>
        private void RegisterRequestDisplaySaveExportMiniLogFileDialogMessage()
        {
            Messenger.Default.Register<int>(this, DataManagementViewModel.RequestDisplaySaveExportMiniLogFileDialogMessageToken, p =>
            {
                try
                {
                    MiniLogHelper.SyncMiniLogFileFromDevice();

                    // If there is device realted message, then it needs to be cleared.
                    MainViewModel.RequestClearErrorMessage();

                    // Get the minilog file directory full name from config file.
                    var localMiniLogFileDirectoryFullName = Path.Combine(Environment.CurrentDirectory, (string)ConfigFileUtility.GetValue(ConfigurationConstant.LocalMiniLogFileDirectoryName));
                    var localMiniLogFileFullName = Path.Combine(localMiniLogFileDirectoryFullName, (string)ConfigFileUtility.GetValue(ConfigurationConstant.MiniLogFileName));

                    var saveFileDialog = ViewHelper.CreateSaveFileDialog("设备数据文件|*" + DataSourceManagementService.ExportMiniLogFileExtension,
                        DataSourceManagementService.ExportMiniLogFileExtension, "保存设备数据文件");
                    saveFileDialog.FileName = (new FileInfo(localMiniLogFileFullName)).Name;

                    if (saveFileDialog.ShowDialog().Value && !string.IsNullOrEmpty(saveFileDialog.FileName))
                    {
                        File.Copy(localMiniLogFileFullName, saveFileDialog.FileName, true);
                        Process.Start(saveFileDialog.FileName);
                    }
                }
                catch (Exception ex)
                {
                    MyViewModelBase.RequestDisplayErrorMessage(ex.Message);
                }
            });
        }

        /// <summary>
        /// Register the CleanDataSourceConfirmMessage from DataManagementViewModel.
        /// </summary>
        private void RegisterCleanDataSourceConfirmMessage()
        {
            Messenger.Default.Register<DialogMessage>(this, DataManagementViewModel.CleanDataSourceConfirmMessageToken, dialog =>
            {
                var confirmResult = MessageBox.Show(dialog.Content, dialog.Caption, dialog.Button, dialog.Icon);
                dialog.ProcessCallback(confirmResult);
            });
        }

        private void ButtonClean_Click(object sender, RoutedEventArgs e)
        {
            var viewModel = DataContext as DataManagementViewModel;
            var password = CleanDataSourcePassword.Password;

            if (viewModel.CleanDataSourceCommand.CanExecute(password))
            {
                viewModel.CleanDataSourceCommand.Execute(password);
            }
            else
            {
                Messenger.Default.Send<string>("输入的密码不正确，请重新输入。", MyViewModelBase.RequestShowMessageBoxMessageToken);
            }

            CleanDataSourcePassword.Focus();
            CleanDataSourcePassword.Password = string.Empty;
            password = CleanDataSourcePassword.Password;
        }
    }
}
